package org.david.code.util;

import java.io.IOException;
import java.util.Map;


import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 读取SQL模板文件工具类* 
 * @author DAVEY
 */
public class TemplateUtils {

	/** 默认编码方式 */
	private static final String DEFAULT_ENCODING = "utf-8";

	private static final String dirPathHeader = "classpath:/";

	/**
	 * 设置模板位置
	 * 
	 * @param dirPath
	 *            模板所在路径
	 * @param fileName
	 *            模板文件名
	 * @throws IOException
	 * @throws TemplateException
	 */
	private static Template getFreemarkerConfiguration(String dirPath,
			String fileName) throws IOException, TemplateException {
		// 根据freemarkerConfiguration的templateLoaderPath载入文件.
		FreeMarkerConfigurationFactoryBean config = new FreeMarkerConfigurationFactoryBean();
		config.setTemplateLoaderPath(dirPathHeader + dirPath);
		Configuration freemarkerConfiguration = config.createConfiguration();
		return freemarkerConfiguration.getTemplate(fileName, DEFAULT_ENCODING);
	}

	/**
	 * 根据模板取得字符串
	 * 
	 * @param dirPath
	 *            模板所在路径
	 * @param fileName
	 *            模板文件名
	 * @param paramMap
	 *            参数列表
	 * @return
	 * @throws MessagingException
	 * @throws IOException
	 * @throws TemplateException
	 */
	@SuppressWarnings("unchecked")
	public static String getContent(String dirPath, String fileName,
			Map<String, Object> paramMap) throws 
			IOException, TemplateException {
		try {
			Template template = getFreemarkerConfiguration(dirPath, fileName);
			String resultStr = FreeMarkerTemplateUtils
					.processTemplateIntoString(template, paramMap);
			return resultStr;
		} catch (IOException e) {
			//throw new MessagingException("template is not found", e);
		} catch (TemplateException e) {
			//throw new MessagingException("read template file ", e);
		}
		return null;
	}
	public static void main(String[] aa){
		System.out.println("你好");
	}

}
